package com.yidian.controller;

import com.yidian.common.constant.QinuiConstant;
import com.yidian.common.entity.Result;
import com.yidian.common.utils.Md5Utils;
import com.yidian.common.utils.QinuiUtils;
import com.yidian.common.utils.RedisUtils;
import com.yidian.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.sql.ResultSet;
import java.util.UUID;

/**
 * @author Superhero
 * @date 2021/12/6 22:04
 */
@RestController
@RequestMapping("/test")
@Api(value = "/test", tags = "测试接口")
public class TestController {

    @Autowired
    private RedisUtils redisUtils;

    @GetMapping("/hello")
    @ApiOperation(value = "测试hello", notes = "测试hello", httpMethod = "GET", response = Result.class)
    public Result<String> hello() {
        return Result.ok("hello");
    }

    @PostMapping("/set/redis/user")
    @ApiOperation(value = "测试Redis添加hello", notes = "测试Redis添加hello", httpMethod = "POST", response = Result.class)
    public Result<String>  setHello() {
        User user = new User();
        user.setId(1L);
        user.setUsername("admin");
        user.setPassword(Md5Utils.getMd5("123456"));
        user.setPhone("13011111111");
        redisUtils.set("user:" + user.getId(), user, RedisUtils.NOT_EXPIRE);
        return Result.ok();
//        return Result.fail();
    }

    @GetMapping("/get/redis/hello/{userId}")
    @ApiOperation(value = "测试Redis获取hello", notes = "测试Redis获取hello", httpMethod = "GET", response = Result.class)
    public Result<User>  getHello(@PathVariable Long userId) {
        User user = redisUtils.get("user:" + userId, User.class);
        return Result.ok(user);
    }

    @PostMapping("/upload/image")
    @ApiOperation(value = "上传文件测试", notes = "上传文件测试", httpMethod = "POST", response = Result.class)
    public Result<String> upload(@RequestParam("imgFile") MultipartFile imgFile) {
        try {
            // 获取原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            int lastIndexOf = originalFilename.lastIndexOf(".");
            // 获取文件houzhui
            String suffix = originalFilename.substring(lastIndexOf - 1);
            // 使用UUID随机生成文件名，防止同名文件覆盖
            String filename = UUID.randomUUID().toString() + suffix;
            QinuiUtils.upload2Qiniu(imgFile.getBytes(), filename);
            // 图片上传成功
            return Result.ok(QinuiConstant.QINUI_URL_PREFIX + filename);
        } catch (Exception e) {
            e.printStackTrace();
            // 图片上传失败
            return Result.fail("上传失败", null);
        }
    }

}
